package com.zhanggm.springcloud.jpa.service;

import com.zhanggm.springcloud.jpa.dao.UserRepositroy;
import com.zhanggm.springcloud.jpa.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepositroy userRepositroy;

    @Override
    public Page<UserEntity> getList(UserEntity userEntity, Integer pageNum, Integer pageSize) {
        Specification<UserEntity> specification = new Specification<UserEntity>() {
            @Override
            public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                //保存查询条件
                List<Predicate> predicates = new ArrayList<>();
                //模糊查询
                if(!StringUtils.isEmpty(userEntity.getUsername())){
                    Predicate username = cb.like(root.get("username"), "%".concat(userEntity.getUsername()).concat("%"));
                    predicates.add(username);
                }
                //等于
                if(!StringUtils.isEmpty(userEntity.getPassword())){
                    Predicate password = cb.equal(root.get("password"), userEntity.getPassword());
                    predicates.add(password);
                }
                //大于等于
                if(userEntity.getStartDate()!=null){
                    Predicate predicate = cb.greaterThanOrEqualTo(root.get("created"), userEntity.getStartDate());
                    predicates.add(predicate);
                }
                //小于等于
                if(userEntity.getEndDate()!=null){
                    Predicate predicate = cb.lessThanOrEqualTo(root.get("created"), userEntity.getEndDate());
                    predicates.add(predicate);
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Pageable pageable = PageRequest.of(pageNum-1,pageSize, Sort.Direction.DESC,"created");
        return userRepositroy.findAll(specification,pageable);
    }
}
